package kr.co.dongpang.android;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.dongpang.domain.ArrayStory;
import com.google.gson.Gson;
import com.sys.app.cms.IdPassword;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DmStoryFragment extends Fragment {

	static class ViewHolder {
		TextView regdate;
		TextView catnm;
		int position;
	}

	ArrayList<ArrayStory> datas = new ArrayList<ArrayStory>();
	
	class JsonReadTask extends AsyncTask<String, Void, Void> {

		String page;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			
			page = params[0];

			String jUrl = "http://dongpang.co.kr/android/dongpang.v01/dm_story.php?id="+IdPassword.getId(getActivity())+"&page=" + page;
			String str = JSONfunctions.getStringfromURL(jUrl);
			Gson gson = new Gson();
			ArrayStory[] datas2 = gson.fromJson(str, ArrayStory[].class);
			for (ArrayStory data : datas2) {
				datas.add(data);
			}	 
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.d("dongpang", "onPostExecute");
			adapter.notifyDataSetChanged();
			super.onPostExecute(result);
		}

	}	
	 
	ListView list;
    MyAdapter adapter;

	public DmStoryFragment(){
		
	}
	
    private static int listPage;
    protected boolean isExistLast;
    
	private Menu menu;
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
	    super.onCreateOptionsMenu(menu, inflater);
	    
	    menu.clear();
		this.menu = menu;

		getActivity().getMenuInflater().inflate(R.menu.story, menu);
		
	}
	
	private static final int WRITE = 0;
	private static final int MODIFY = 1;
	 
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    
	    if(item.getTitle().equals("write")){
	    	Intent intent = new Intent(getActivity(), DmStoryWrite.class);
	    	startActivityForResult(intent, WRITE);
	    }
	    
	    return super.onOptionsItemSelected(item);
	}    
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
		setHasOptionsMenu(true);
		
        View rootView = inflater.inflate(R.layout.sm_interest, container, false);
        ((ActionBarActivity)getActivity()).getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		list = (ListView)rootView.findViewById(R.id.list);
		
		listPage = 0;

		// Getting adapter by passing xml data ArrayList
		adapter = new MyAdapter(getActivity(), R.layout.dm_story_row, datas);
        list.setAdapter(adapter);   
		list.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				final int lastItem = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount) {
					if (isExistLast == false) {
						isExistLast = true;
						Log.d("Last", "Last");
						new JsonReadTask().execute("" + listPage++, null, null);
						Log.d("Last", "Last:"+listPage);
					}
				} else {
					if (isExistLast == true) {
						isExistLast = false;
					}
				}
			}
		});

		if (datas == null || datas.size() == 0) {
			new JsonReadTask().execute(String.valueOf(listPage++), null, null); 
		}              
        
        return rootView;
    }
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		switch (requestCode) {
		case WRITE: {
			datas.clear();
			listPage = 0;
			new JsonReadTask().execute(String.valueOf(listPage++), null, null);
			break;
		}	
		case MODIFY: {
			datas.clear();
			listPage = 0;
			new JsonReadTask().execute(String.valueOf(listPage++), null, null);
			break;
		}		
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}

	class MyAdapter extends ArrayAdapter<ArrayStory> {
		
		protected static final int REQUEST_DETAIL = 0;

		public MyAdapter(Context context, int resource, ArrayList<ArrayStory> items) {
			super(context, resource, items);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(R.layout.dm_story_row, null);
			}
		
			
			((TextView)convertView.findViewById(R.id.MD)).setText(getItem(position).MD);
			((TextView)convertView.findViewById(R.id.APM)).setText(getItem(position).APM);
			((TextView)convertView.findViewById(R.id.message)).setText(getItem(position).message);
			
			convertView.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub 
					
					Intent intent = new Intent(getActivity(), DmStoryModify.class);
					intent.putExtra("sno", getItem(position).sno);
					intent.putExtra("message", getItem(position).message);
					startActivityForResult(intent, MODIFY);
				}
				
			});
			
			return convertView;
		}

	}	
	
	
	
	
	
	
}
